import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { Dialog } from 'vant'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login'),
    meta: { requiresAuth: false }
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('@/views/search'),
    meta: { requiresAuth: false }
  },
  {
    path: '/article/:articleId',
    name: 'article',
    component: () => import('@/views/article'),
    // 将路由动态参数映射到组件的 props 中，更推荐这种做法
    props: true,
    meta: { requiresAuth: false }
  },
  {
    path: '/user/profile',
    component: () => import('@/views/user-profile'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'layout',
    component: () => import('@/views/layout'),
    meta: { requiresAuth: false },
    children: [
      {
        path: '', // 默认子路由
        name: 'home',
        component: () => import('@/views/home'),
        meta: { requiresAuth: false }
      },
      {
        path: 'qa',
        name: 'qa',
        component: () => import('@/views/qa'),
        meta: { requiresAuth: true }
      },
      {
        path: 'video',
        name: 'video',
        component: () => import('@/views/video'),
        meta: { requiresAuth: true }
      },
      {
        path: 'my',
        name: 'my',
        component: () => import('@/views/my'),
        meta: { requiresAuth: false }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 所有路由跳转之前都会走 beforeEach
router.beforeEach(async (to, from, next) => {
  // 是否需要权限
  if (to.meta.requiresAuth) {
    // 检测是否登录
    // 已登录直接放行
    if (store.state.user) return next()
    // 未登录提示是否登录
    const r = await Dialog.confirm({
      title: '提示',
      message: '需要登录才能访问，是否登录？'
    }).catch(e => e)
    if (r === 'confirm') {
      // login();
      next('/login')
    } else {
      // 中断
      next(false)
    }
  } else {
    next()
  }
})

export default router
